<?php
// +----------------------------------------------------------------------
// | RXThinkCMF_EVTP6_PRO前后端分离旗舰版框架 [ RXThinkCMF ]
// +----------------------------------------------------------------------
// | 版权所有 2021 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.rxthink.cn
// +----------------------------------------------------------------------
// | 作者: 牧羊人 <rxthinkcmf@163.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\service;


use app\admin\model\RoomList;
use think\facade\Db;

/**
 * 自习室列管理-服务类
 * @author 牧羊人
 * @since: 2021/12/24
 * Class RoomListService
 * @package app\adminmini\service
 */
class RoomListService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new RoomList();
    }


    public function getList()
    {
        $param = request()->param();
        // 查询条件
        $map = [];
        // 自习室名称
        $name = isset($param['room_name']) ? trim($param['room_name']) : '';
        if ($name) {
            $map[] = ['room_name', 'like', "%{$name}%"];
        }
        $mobile = isset($param['mobile']) ? trim($param['mobile']) : '';
        if ($mobile) {
            $map[] = ['mobile', 'like', "%{$mobile}%"];
        }
        $type = isset($param['type']) ? trim($param['type']) : '';
        if ($type) {
            $map[] = ['type', '=', $type];
        }
        $map[] = ['mark', '=', 1];
        $list = Db::name('mini_room_list')
            ->alias('o')
            ->where($map)->order('id desc')->page(PAGE, PERPAGE)
            ->select();

        foreach ($list as $i => $info) {
            $infodata = Db::name('mini_room_list_distribution')->where('store_id', $info['id'])->find();

            if ($infodata) {
                if (intval($infodata['direct_id']) > 0) {
                    $room = Db::name('mini_room_list')->where('id', $infodata['direct_id'])->find();
                    $info['referrer'] = $room['room_name'];
                }
            }

            if (intval($info['direct_num']) < 7 && intval($info['direct_num']) > 0) {
                $info['grade'] = '加盟店长';
                if ($info['is_long'] == 1) {
                    $info['grade'] = '加盟店长--区域店长';
                }
            }
            if (intval($info['is_long']) == 1) {
                $info['grade'] = '区域店长';
            }
            if (intval($info['direct_num']) > 6) {
                $info['grade'] = '大区店长';
                if (intval($info['is_long']) == 1) {
                    $info['grade'] = '大区店长--区域店长';
                }
            }

            switch ($info['status']) {
                case 1:
                    $info['status_name'] = "营业中";
                    break;
                case 2:
                    $info['status_name'] = "装修中";
                    break;
                case 3:
                    $info['status_name'] = "筹备中";
                    break;
                case 0:
                    $info['status_name'] = "装修中";
            }
            switch ($info['type']) {
                case 1:
                    $info['type_name'] = "自主加盟商户";
                    break;
                case 2:
                    $info['type_name'] = "联营合作商户";
                    break;
                case 3:
                    $info['type_name'] = "棋乐直营店";
                    break;
                case 0:
                    $info['type_name'] = " ";
            }

            if (intval($info['direct_num']) > 6 && intval($info['second_num']) > 30) {


                $num = Db::name('mini_room_list')->where('direct_id', $info['id'])->where('direct_num', '>', 14)->count();


                $unm = $info['direct_num'] + $info['second_num'] + $info['leve_num'];


                if ($unm > 41) {
                    if ($num > 1) {
                        $info['grade'] = '合伙人';
                        if ($info['is_long'] == 1) {
                            $info['grade'] = '合伙人--区域店长';
                        }
                    }

                }

            }

            // 城市
            $city = [];
            $city[] = !empty($info['province_code']) ? strval($info['province_code']) : "";
            $city[] = !empty($info['city_code']) ? strval($info['city_code']) : "";
            $city[] = !empty($info['district_code']) ? strval($info['district_code']) : "";
            $info['city'] = $city;
            $info['curl'] = 'http://adminminiqixuke.qishenghui.net' . '/login?username=' . $info['username'] . '&password=' . $info['password'];

            $list[$i] = $info;
        }
        $count = Db::name('mini_room_list')
            ->alias('o')
            ->where($map)->page(PAGE, PERPAGE)->count();
        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );
        return $message;

    }

    public function generateRandomString($length = 6)
    {

        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        $charactersLength = strlen($characters);

        $randomString = '';

        for ($i = 0; $i < $length; $i++) {

            $randomString .= $characters[rand(0, $charactersLength - 1)];

        }

        return $randomString;

    }

    /**
     * 添加或编辑
     * @param $userId
     * @return array
     */
    public function edit()
    {
        // 参数
        $data = request()->param();


        // 门店轮播图处理

        unset($data['make_image']);
        unset($data['head_url']);
        // 城市数据处理
        $city = isset($data['city']) ? $data['city'] : [];
        if (!empty($city)) {
            $data['province_code'] = $city[0];
            $data['city_code'] = $city[1];

            if (isset($city[2])) {
                $data['district_code'] = $city[2];
            } else {
                $data['district_code'] = 0;
            }
            unset($data['city']);
        } else {
            $data['province_code'] = 0;
            $data['city_code'] = 0;
            $data['district_code'] = 0;
        }


        //添加权限

        if ($data['province_code']) {

            if ($data['province_code']) {
                $infolist['province_name'] = Db::name('city')->where('citycode', $data['province_code'])->find();
            }

            if ($data['city_code']) {
                $infolist['city_name'] = Db::name('city')->where('citycode', $data['city_code'])->find();
            }
            if (($data['district_code']) > 0) {

                $infolist['district_name'] = Db::name('city')->where('citycode', $data['district_code'])->find();

                if (!isset($infolist['district_name']['name'])) {
                    $infolist['district_name']['name'] = '';
                }

            } else {
                $infolist['district_name']['name'] = '';
            }

            $infolist['address_lan'] = $infolist['province_name']['name'] . $infolist['city_name']['name'] . $infolist['district_name']['name'] . $data['address'];
        }

        $id = getter($data, "id", 0);


        $count = $this->model
            ->where("mobile", '=', $data['mobile'])
            ->where("id", "<>", $id)
            ->where("mark", "=", 1)
            ->count();
//        if ($count > 0) {
//            return message("系统中已存在相同的手机号", false);
//        }
        // 添加时设置密码
        if (empty($id)) {

            // 用户名重复性验证
            $count = $this->model
                ->where("username", '=', $data['username'])
                ->where("mark", "=", 1)
                ->count();
            $data['invitation_code'] = $this->generateRandomString();
            if ($count > 0) {
                return message("系统中已存在相同的用户名", false);
            }
        } else {
            // 用户名重复性验证
            $count = $this->model
                ->where("username", '=', $data['username'])
                ->where("id", "<>", $id)
                ->where("mark", "=", 1)
                ->count();
            if ($count > 0) {
                return message("系统中已存在相同的用户名", false);
            }

            // 获取用户信息
            $info = Db::name('mini_room_list')->where('id', $data['id'])->find();


            if (!$info) {
                return message("用户信息不存在", false);
            }

        }


        // 查询当亲小程序类型
        $error = "";
        $result = $this->model->edit($data, $error);

        $info = Db::name('mini_room_list_distribution')->where('store_id', $result)->find();

        if (empty($info)) {
            //记录关系值
            $das = array(
                'indirect_id' => 0,
                'direct_id' => 0,
                'introduction_id' => 0,
                'store_id' => $result,
                'create_time' => time(),
            );

            Db::name('mini_room_list_distribution')->insert($das);
        }

        if (!isset($result)) {
            return message('资料未修改', false);
        }

        $store_name = $data['room_name'];
        unset($data['room_name']);
        unset($data['note']);


        if (isset($data['district_code'])) {
            $da = Db::name('mini_room_list')->where('district_code', $data['district_code'])->find();

            if ($da['id'] != $result) {
                $da['is_long'] = 1;
                Db::name('mini_room_list')->where('id', $da['id'])->update($da);
            }
        }

        if (isset($data['in_code'])) {
            if ($data['in_code'] != "") {

                $info = Db::name('mini_alliance')->where('mobile', $data['mobile'])->where('invitation_code', $data['in_code'])->find();

                if (!$info) {

                    $da0 = Db::name('mini_room_list')->where('invitation_code', $data['in_code'])->find();


                    if ($da0) {

                        $datas = array(
                            'name' => $data['name'],
                            'mobile' => $data['mobile'],
                            'address' => $data['address'],
                            'create_time' => time(),
                            'invitation_code' => isset($data['in_code']) ? $data['in_code'] : '',
                        );
                        Db::name('mini_alliance')->insert($datas);
                    }
                }

            }
        }
        unset($data['in_code']);
        // 推荐人
        if (isset($data['in_code'])) {
            if ($data['in_code'] != "") {
                $info = Db::name('mini_alliance')->where('mobile', $data['mobile'])->where('invitation_code', $data['in_code'])->find();
            } else {
                $info = Db::name('mini_alliance')->where('mobile', $data['mobile'])->find();
            }
        } else {
            $info = Db::name('mini_alliance')->where('mobile', $data['mobile'])->find();
        }
        $da1 = array();
        $da = array();
        $da2 = array();
        if ($info) {

            unset($data['note']);
            if ($info['invitation_code']) {
                $da0 = Db::name('mini_room_list')->where('invitation_code', $info['invitation_code'])->find();


                $distribution = Db::name('mini_room_list_distribution')->where('direct_id', $da0['id'])->where('store_id', $result)->find();
                if (!$distribution) {
                    $das['direct_id'] = $da0['id'];
                    $num['direct_num'] = $da0['direct_num'] + 1;
                    Db::name('mini_room_list')->where('id', $result)->update($das);
                    Db::name('mini_room_list')->where('invitation_code', $info['invitation_code'])->update($num);
                }
                $da0 = Db::name('mini_room_list')->where('invitation_code', $info['invitation_code'])->find();
                if ($da0) {
                    if ($da0['direct_id'] > 0) {
                        $da1 = Db::name('mini_room_list')->where('id', $da0['direct_id'])->find();
                        $distribution = Db::name('mini_room_list_distribution')->where('direct_id', $da1['id'])->where('store_id', $result)->find();
                        if (!$distribution) {
                            $das['second_id'] = $da1['id'];
                            $num1['second_num'] = $da1['second_num'] + 1;
                            Db::name('mini_room_list')->where('id', $result)->update($das);
                            Db::name('mini_room_list')->where('id', $da1['id'])->update($num1);
                        }

                    }
                }


                if ($da1) {
                    if ($da1['direct_id'] > 0) {
                        $da2 = Db::name('mini_room_list')->where('id', $da1['direct_id'])->find();
                        $distribution = Db::name('mini_room_list_distribution')->where('introduction_id', $da2['id'])->where('direct_id', $da1['id'])->where('store_id', $result)->find();

                        if (!$distribution) {
                            $das['leve_id'] = $da2['id'];
                            $num2['leve_num'] = $da2['leve_num'] + 1;
                            Db::name('mini_room_list')->where('id', $result)->update($das);
                            Db::name('mini_room_list')->where('id', $da2['id'])->update($num2);
                        }
                    }
                }
                unset($data['note']);
                $info = Db::name('mini_room_list_distribution')->where('store_id', $result)->find();

                if (!empty($info)) {

                    //记录关系值
                    $das = array(
                        'indirect_id' => isset($da1['id']) ? $da1['id'] : 0,
                        'direct_id' => isset($da0['id']) ? $da0['id'] : 0,
                        'introduction_id' => isset($da2['id']) ? $da2['id'] : 0,
                        'store_id' => $result,
                        'create_time' => time(),
                    );


                    Db::name('mini_room_list_distribution')->where('store_id', $result)->update($das);
                } else {

                    unset($data['note']);
                    //记录关系值
                    $das = array(
                        'indirect_id' => isset($da1['id']) ? $da1['id'] : 0,
                        'direct_id' => isset($da0['id']) ? $da0['id'] : 0,
                        'introduction_id' => isset($da2['id']) ? $da2['id'] : 0,
                        'store_id' => $result,
                        'create_time' => time(),
                    );

                    Db::name('mini_room_list_distribution')->insert($das);
                }


            }
        }

        unset($data['num']);
        unset($data['note']);
        unset($data['room_name']);


        if (empty($id)) {
            $ue = $this->model
                ->where("username", '=', $data['username'])
                ->where("mark", "=", 1)
                ->where("mobile", '=', $data['mobile'])->find();
        } else {
            $ue = Db::name('mini_room_list')->where('id', $data['id'])->find();


        }


        $infoda = Db::table('evt_customer_user')->where('room_id', $ue['id'])->where('username', '=', $data['username'])->find();

        if (!$infoda) {

            $da['username'] = $data['username'];
            $da['password'] = get_password($data['password']);
            $da['mobile'] = $data['mobile'];
            $da['nickname'] = $store_name;
            $da['realname'] = $data['name'];
            $da['room_id'] = $ue['id'];

            $user_id = Db::table('evt_customer_user')->insertGetId($da);
            $role = array(
                'name' => '超级管理员',
                'status' => 1,
                'room_id' => $user_id,
                'note' => '超级管理员',
            );

            Db::table('evt_customer_role')->insert($role);

            $role = Db::table('evt_customer_role')->where('room_id', '=', $user_id)->find();;
            $user_role = array(
                'user_id' => $user_id,
                'role_id' => $role['id'],
            );
            Db::table('evt_customer_user_role')->insert($user_role);
            $list = Db::table('evt_customer_menu')->select();;
            foreach ($list as $i => $v) {
                $role_menu = array(
                    'role_id' => $role['id'],
                    'menu_id' => $v['id'],
                );
                Db::table('evt_customer_role_menu')->insert($role_menu);

            }
            $role = array(
                'name' => '保洁',
                'status' => 1,
                'room_id' => $user_id,
                'note' => '保洁',
            );
            Db::table('evt_customer_role')->insert($role);
            $role = Db::table('evt_customer_role')->where('room_id', '=', $user_id)->where('name', '保洁')->find();;
            $user_role = array(
                'user_id' => $user_id,
                'role_id' => $role['id'],
            );
            Db::table('evt_customer_user_role')->insert($user_role);
            $list = Db::table('evt_customer_menu')->where('id', 'in', [2172, 2110, 2173])->select();
            foreach ($list as $i => $v) {
                $role_menu = array(
                    'role_id' => $role['id'],
                    'menu_id' => $v['id'],
                );
                Db::table('evt_customer_role_menu')->insert($role_menu);

            }
        } else {

            $da['username'] = $data['username'];

            $da['mobile'] = $data['mobile'];
            $da['nickname'] = $store_name;
            $da['realname'] = $data['name'];
            $da['mark'] = 1;
            if (isset($data['password'])) {
                if ($data['password'] != "") {
                    $da['password'] = get_password($data['password']);
                    Db::table('evt_customer_user')->where('id', $infoda['id'])->update($da);
                } else {
                    Db::table('evt_customer_user')->where('id', $infoda['id'])->update($da);
                }
            }
        }

        cache('room', false);
        return message("操作成功", true);
    }

    public function object_array($array)
    {
        if (is_object($array)) {
            $array = (array)$array;
        }
        if (is_array($array)) {
            foreach ($array as $key => $value) {
                $array[$key] = object_array($value);
            }
        }
        return $array;
    }

    public function delete()
    {
        $param = request()->param();
        // 记录ID
        $ids = getter($param, "id");
        if (empty($ids)) {
            return message("记录ID不能为空", false);
        }
        if (is_array($ids)) {
            // 批量删除
            $result = $this->model->deleteDAll($ids);
            if (!$result) {
                return message("删除失败", false);
            }
            Db::table('evt_customer_user')->where('room_id', 'in', $ids)->delete();
            return message("删除成功");
        } else {
            // 单个删除
            $info = $this->model->getInfo($ids);
            if ($info) {
                $result = $this->model->drop($ids);
                if ($result !== false) {
                    Db::table('evt_customer_user')->where('room_id', 'in', $ids)->delete();
                    return message();
                }
            }
            return message($this->model->getError(), false);
        }
    }
}